{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"http://hilpisch.com/tpq_logo.png\" alt=\"The Python Quants\" width=\"35%\" align=\"right\" border=\"0\"><br><br><br>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Listed Volatility and Variance Derivatives\n",
    "\n",
    "**Wiley Finance (2017)**\n",
    "\n",
    "Dr. Yves J. Hilpisch | The Python Quants GmbH\n",
    "\n",
    "http://tpq.io | [@dyjh](http://twitter.com/dyjh) | http://books.tpq.io\n",
    "\n",
    "<img src=\"http://hilpisch.com/../images/lvvd_cover.png\" alt=\"Derivatives Analytics with Python\" width=\"30%\" align=\"left\" border=\"0\">"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Model-Free Replication of Variance"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Although volatility derivatives, variance swaps and futures are considered second generation derivatives (since they are defined on volatility and variance directly), some of the most elegant and robust results of quantitative finance apply to these kinds of derivatives. In particular, it is possible to statically replicate realized variance without using any kind of specific model. This, for example, does not apply to most other important concepts in option pricing and trading, like implied volatility or delta hedging of options."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This chapter covers mainly the following topics:\n",
    "\n",
    "* **spanning with options**: Breeden and Litzenberger (1978) already in the 1970s showed how to replicate state-contingent payoffs (satisfying certain conditions) by using positions in options\n",
    "* **log contracts**: an important piece in the replication of (realized) variance and the valuation of variance swaps are so-called log contracts\n",
    "* **static replication of variance**: this is about the central result of replicating realized variance by a log contract as well as static positions in options\n",
    "* **derivatives with constant dollar gamma**: in the replication and valuation of variance swaps, constant dollar gamma positions play a central role\n",
    "* **practical replication of variance swaps**: using the theoretical insights and results, the chapter also illustrates the generation of constant dollar gamma positions and therewith the practical replication of variance swaps based on numerical examples\n",
    "* **VSTOXX as volatility index**: using the central result, the final section in this chapter explains and justifies the definition of the VSTOXX volatility index (and the VIX index to this end)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The theoretical parts of this chapter roughly follow the lines of chapter 11 of Gatheral (2006). Since they are of importance for both volatility and variance derivatives we have put them up front and present them in a connected fashion."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Spanning with Options"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Breeden and Litzenberger (1978) use option prices to derive prices for *elementary securities*, i.e. securities that pay exactly 1 unit of currency at a certain future date given a certain state of the economy. In economics, *Arrow-Debreu security* is also a common term. The prices of elementary securities are generally called *state prices*. Having state prices available, every other contingent claim can be priced by multiplying the contingent claim's state-dependent payoff by the respective state prices."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let $t \\geq 0$ denote the current date and $T>t$ the future date of interest (e.g. maturity of a derivative instrument). For simplicity, states of the economy should be distinguished by the level of a stock index $S$ only. Let $p(S_{T},T;S_{t},t)$ denote the *state price* given a stock index level of $S_{t}$ at $t$ for a stock index level $S_{T}$ at $T$, then:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "$$\n",
    "p(S_{T},T;S_{t},t)=\\left. \\frac{\\partial^{2} P(S_{t},K,T)}{\\partial K^{2}}\\right|_{S_{T}=K}=\\left. \\frac{\\partial^{2} C(S_{t},K,T)}{\\partial K^{2}}\\right|_{S_{T}=K}\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here, $P$ and $C$ represent prices (given by some pricing formula) of European put and call options, respectively. Therefore, a state price can be derived by taking the second partial derivative of an option pricing formula with respect to the strike of the option. Equipped with these state prices, the value of a state-contingent claim with payoff function $g(S_{T})$ is\n",
    "\n",
    "\\begin{eqnarray}\n",
    "\\mathbf{E}_{t}(g(S_{T})|S_{t})&=& \\int_{0}^{\\infty}g(K)p(K,T;S_{t},t)dK\\nonumber \\\\\n",
    "&=&\\int_{0}^{F} g(K) \\frac{\\partial^{2} P(S_{t},K,T)}{\\partial K^{2}} dK + \\int_{F}^{\\infty} g(K) \\frac{\\partial^{2} C(S_{t},K,T)}{\\partial K^{2}} dK\\nonumber\n",
    "\\end{eqnarray}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "with $F$ being the $T$-forward price of the index at $t$ (see Breeden and Litzenberger (1978))."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We now apply integration by parts. With $u = u(x), v = v(x), du = u'(x)dx, dv=v'(x)dx$, integration by parts states that\n",
    "\n",
    "$$\n",
    "\\int u(x)v'(x)dx=u(x)v(x)-\\int u'(x)v(x)dx \n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Therefore, we get\n",
    "\n",
    "\\begin{eqnarray}\n",
    "\\mathbf{E}_{t}(g(S_{T})|S_{t}) &=& \\left. g(K) \\frac{\\partial P(S_{t},K,T)}{\\partial K} \\right|_{0}^{F}\n",
    " - \\int_{0}^{F} g'(K) \\frac{\\partial P(S_{t},K,T)}{\\partial K} dK \\nonumber \\\\\n",
    "&+& \\left. g(K) \\frac{\\partial C(S_{t},K,T)}{\\partial K}\\right|_{F}^{\\infty} - \\int_{F}^{\\infty} g'(K) \\frac{\\partial C(S_{t},K,T)}{\\partial K} dK\\nonumber \\\\\n",
    "&=& g(F)- \\int_{0}^{F} g'(K) \\frac{\\partial P(S_{t},K,T)}{\\partial K} dK - \\int_{F}^{\\infty} g'(K) \\frac{\\partial C(S_{t},K,T)}{\\partial K} dK\\nonumber\n",
    "\\end{eqnarray}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Applying integration by parts once again yields\n",
    "\n",
    "\\begin{eqnarray}\n",
    "\\mathbf{E}_{t}(g(S_{T})|S_{t})\n",
    "&=& g(F) - \\left. g'(K) P(S_{t},K,T)\\right|_{0}^{F} + \\int_{0}^{F} g''(K) P(S_{t},K,T) dK\\nonumber\\\\\n",
    " &-& \\left. g'(K) C(S_{t},K,T)\\right|_{F}^{\\infty} + \\int_{F}^{\\infty} g''(K) C(S_{t},K,T) dK \\nonumber\\\\\n",
    " &=& g(F) + \\int_{0}^{F} g''(K) P(S_{t},K,T) dK\n",
    " + \\int_{F}^{\\infty} g''(K) C(S_{t},K,T) dK \\nonumber\n",
    "\\end{eqnarray}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As is evident from this last equation, in this setting any twice continuously differentiable payoff $g$ due at $T$ can be replicated by infinite strips of European put and call options maturing at $T$. In other words, these options span the space of twice continuously differentiable payoffs."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Log Contracts"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So-called *log contracts* are a kind of derivative instrument that plays an important role in the valuation of variance swaps. Recall that a long position in a variance contract pays at maturity the difference between the realized variance over the life time of the swap and an up front fixed variance strike."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Consider the payoff $g(S_{T})=\\log \\frac{S_{T}}{F} = \\log S_T - \\log F$. Then\n",
    "\n",
    "\\begin{eqnarray}\n",
    "g'(S_{T})&=&\\frac{1}{S_{T}}\\nonumber\\\\\n",
    "g''(S_{T})&=&-\\frac{1}{S_{T}^ 2}\\nonumber\n",
    "\\end{eqnarray}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Valuing this contract by making use of the option spanning approach yields\n",
    "\n",
    "\\begin{eqnarray}\n",
    "\\mathbf{E}\\left(\\left.\\log\\frac{S_{T}}{F}\\right| S_{t}\\right)\n",
    "&=& \\log\\frac{F}{F} + \\int_{0}^{F} -\\frac{1}{K^{2}} P(S_{t},K,T) dK\n",
    " + \\int_{F}^{\\infty} -\\frac{1}{K^{2}} C(S_{t},K,T) dK\\nonumber\\\\\n",
    "  &=& -\\int_{0}^{F} P(S_{t},K,T) \\frac{dK}{K^{2}}\n",
    " - \\int_{F}^{\\infty} C(S_{t},K,T) \\frac{dK}{K^{2}} \\nonumber\n",
    "\\end{eqnarray}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As a consequence, the log contract can be replicated by (infinite strips of) European put and call options on the underlying. Every option is weighted by the square of the strike."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Static Replication of Realized Variance and Variance Swaps"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Assume for simplicity zero short rates such that $F=S_{t}$. For $t=0$, one has "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\\begin{eqnarray*}\n",
    "\\log\\frac{S_{T}}{F}&=&\\log\\frac{S_{T}}{S_{0}}\\nonumber\\\\\n",
    "&=& \\int_{0}^{T} d\\log(S_{t})\\\\\n",
    "&=& \\int_{0}^{T} \\frac{dS_{t}}{S_{t}}-\\int_{0}^{T} \\frac{\\sigma^{2}(S_{t})}{2}dt\n",
    "\\end{eqnarray*}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Compare this result with those for the discrete delta hedging (chapter _Derivatives, Volatility and Variance_). Such a comparison further illustrates the connection between the (discrete) delta hedging of an option and (the valuation of) variance swaps."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Above, the fact is used that the *total return* over the interval $[0,T]$ equals the integral over the marginal returns of $S$ for the same time interval. The second term in the last equation results from the application of Itô's lemma. This term is equal to half of the total variance of $S$ over the time interval $[0,T]$. Taking the risk-neutral expectation of that expression gives\n",
    "\n",
    "$$\n",
    "\\mathbf{E}\\left( \\int_{0}^{T}\\sigma^{2}(S_{t})dt \\right)= -2\\mathbf{E}\\left(\\log\\frac{S_{T}}{F} \\right)\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Combining the results about the the log contract replication and valuation with this last insight shows that realized variance is given in a model-free manner through the prices of European put and call options. This is due to the fact that realized variance can be replicated by the use of a log contract."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Constant Dollar Gamma Derivatives and Portfolios"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Above, we establish the replication of realized variance by the log contract. The log contract has, as a defining characteristic, a *constant dollar gamma*. The *gamma* of a derivative defined on some underlying $S$ with value $f_t(S_t)$ is defined as\n",
    "\n",
    "$$\\Gamma_t = \\frac{\\partial^2 f_t}{\\partial S_t^2}$$\n",
    "\n",
    "i.e. the second partial derivative of the pricing function with respect to the value of the underlying (assuming that the pricing function indeed is twice continuously differentiable)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Its *dollar gamma* is then defined by the product of the gamma and the square of the value of the underlying (sometimes the factor 0.5 is added)\n",
    "\n",
    "$$\\Gamma^{\\$}_t \\equiv \\Gamma_t \\cdot S^2_t$$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Omitting the time index, a constant dollar gamma implies, for some fixed value $a$, a gamma of\n",
    "\n",
    "\\begin{eqnarray*}\n",
    "\\Gamma^{\\$} = \\Gamma \\cdot S^2 &\\equiv&  a \\\\\n",
    "\\Leftrightarrow \\Gamma &=& \\frac{a}{S^2}\n",
    "\\end{eqnarray*}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We therefore have \n",
    "\n",
    "$$\n",
    "\\frac{\\partial^2 f}{\\partial S^2} = \\frac{a}{S^2}\n",
    "$$\n",
    "\n",
    "This partial differential equation has a solution of the form\n",
    "$$\n",
    "f(S) = a \\log(S) + bS + c\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Indeed, the log contract fits trivially into the general solution by setting $a=1, b=0, c=0$, i.e.\n",
    "\n",
    "$$\n",
    "f(S) = \\log(S)\n",
    "$$\n",
    "\n",
    "illustrating its importance."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With $\\hat{\\sigma}^2$ being the realized variance and $\\sigma_K^2$ being the fixed variance strike, a long position in a *variance swap* (with notional of 1 currency unit), pays at expiry\n",
    "\n",
    "$$\n",
    "\\hat{\\sigma}^2 - \\sigma_K^2\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With this payoff, we get a replicating portfolio of\n",
    "\n",
    "$$\n",
    "f_t(S_t) = 2 \\log(S_t) + e^{-r(T-t)} \\sigma_K^2\n",
    "$$\n",
    "\n",
    "i.e. $a=2, b = 0, c = e^{-r(T-t)} \\sigma_K^2$. A variance swap therefore also has a constant dollar gamma. This insight is used in the next section."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Practical Replication of Realized Variance"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Consider the Black-Scholes-Merton (1973) model economy (no dividends) with the present value of a European call option given by\n",
    "\n",
    "\\begin{eqnarray*}\n",
    "C(S, K, t, T, r, \\sigma) &=& S_{t} \\cdot \\mathbf{N}(d_{1})-e^{-r(T-t)} \\cdot K \\cdot \\mathbf{N}(d_{2}) \\\\\n",
    "\\mathbf{N}(d)&=&\\frac{1}{\\sqrt{2\\pi}}\\int_{-\\infty}^{d}e^{-\\frac{1}{2}x^{2}}dx \\\\\n",
    "d_{1}&=&\\frac{\\log \\frac{S_{t}}{K}+(r+\\frac{\\sigma^{2}}{2})(T-t)}{\\sigma \\sqrt{T-t}} \\\\\n",
    "d_{2}&=&\\frac{\\log \\frac{S_{t}}{K}+(r-\\frac{\\sigma^{2}}{2})(T-t)}{\\sigma \\sqrt{T-t}}\n",
    "\\end{eqnarray*}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here, $S_t$ is the index level at date $t$, $K$ is the option strike, $T$ date of maturity (in year fractions), $r$ the constant, risk-less short rate and $\\sigma$ the instantaneous volatility.\n",
    "\n",
    "The *gamma* of an option in this model is given as follows\n",
    "\n",
    "$$\\Gamma_t = \\frac{\\partial^2 C_t}{\\partial S_t^2} = \\frac{\\mathbf{N}'(d_1)}{S_t \\sigma \\sqrt{T-t}}$$\n",
    "\n",
    "with\n",
    "\n",
    "$$\\mathbf{N}'(d) = \\frac{1}{\\sqrt{2\\pi}} e^{-\\frac{1}{2} x^2}$$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Our aim in this section is to build a **portfolio of European call options** with a constant dollar gamma, i.e. $\\Gamma^{Portfolio} \\cdot S_t^2 \\equiv a$ for some fixed value $a$."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The Python function `dollar_gamma` implements the dollar gamma formula for the European call option."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "import math\n",
    "import numpy as np\n",
    "import scipy.stats as scs\n",
    "def dollar_gamma(St, K, t, T, r, sigma):\n",
    "    ''' Returns European call option dollar gamma. '''\n",
    "    d1 = ((np.log(St / K) + (r + 0.5 * sigma ** 2) * (T - t))\n",
    "              / sigma * math.sqrt(T - t))\n",
    "    gamma = scs.norm.pdf(d1) / (St * sigma * math.sqrt(T - t))\n",
    "    return gamma * St ** 2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let us parametrize the financial model for $t=0$, leaving the values for the initial index level $S_0$ and for the option strike $K$ undefined for the moment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "t = 0.0  # curent date in year fractions\n",
    "T = 1.0  # maturity in year fractions\n",
    "r = 0.01  # constant risk-less short rate\n",
    "sigma = 0.2  # instantenous volatility"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we can calculate the dollar gamma values for different strikes of the European call options over a range, respectively, of initial values for the index level."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "import pandas as pd \n",
    "from pylab import plt, mpl\n",
    "plt.style.use('seaborn')\n",
    "mpl.rcParams['font.family'] = 'serif'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "gammas = pd.DataFrame()\n",
    "## 300 data points over the range form 0 to 300\n",
    "s_range = np.linspace(0.0001, 300, 300)\n",
    "strike_range = range(25, 226, 25)\n",
    "for K in strike_range:\n",
    "    gammas['K=%d' % K] = dollar_gamma(s_range, K, t, T, r, sigma)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For every strike level gamma values for 300 different initial values of the stock index have been calculated and collected. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gammas.info()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Having the data stored in a pandas ``DataFrame`` object, the results are easily visualized. From the following figure, you can see that dollar gamma is more pronounced the higher the strike of the option. A doubling of the strike leads to a doubling of the maximum dollar gamma value which is always achieved at the ATM level (see strikes 25, 50, 100, 200)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "gammas.plot(figsize=(10, 5), cmap='coolwarm')\n",
    "plt.xlabel('index level')\n",
    "plt.ylabel('dollar gamma');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<p style=\"font-family: monospace;\">Dollar gamma values for different strikes and 300 different initial stock index values.</p>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let us check what happens when we add all dollar gamma values up by simply composing a portfolio in which every option has weight 1 or equal weight."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "gammas['sum'] = gammas.sum(axis=1)\n",
    "gammas.plot(figsize=(10, 5), cmap='coolwarm')\n",
    "plt.xlabel('index level')\n",
    "plt.ylabel('dollar gamma');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<p style=\"font-family: monospace;\">Dollar gamma values added over the range of 300 different initial index levels.</p>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Obviously, given the previous figure, the dollar gamma of the portfolio of equally weighted options is all but constant. Let us try a different weighting scheme that attaches a higher weight to smaller strikes and a lower weight to higher strikes. To this end, we divide all dollar gamma values by the strike *K*. This brings all maximum dollar gamma values in line (to two in this case)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "gammas_k = pd.DataFrame()\n",
    "for K in strike_range:\n",
    "    gammas_k['K=%d' % K] = dollar_gamma(s_range, K, t, T, r, sigma) / K\n",
    "gammas_k['sum'] = gammas_k.sum(axis=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "gammas_k.plot(figsize=(10, 5), cmap='coolwarm')\n",
    "plt.xlabel('index level')\n",
    "plt.ylabel('$K$ weighted dollar gamma');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<p style=\"font-family: monospace;\">Strike-weighted, added Dollar Gamma values."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "According to the previous figure this seems to be a bit better in the sense that we still do not have a constant dollar gamma but at least a range where dollar gamma is linear (mainly between strikes of 75 and 150).  Therefore, let us  weight the dollar gammas by the square of the strike (something we have already seen in the replication result for log contract). In this case the highest dollar gamma values are observed for the lowest strikes and vice versa."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "gammas_k2 = pd.DataFrame()\n",
    "for K in strike_range:\n",
    "    gammas_k2['K=%d' % K] = dollar_gamma(s_range, K, t, T, r, sigma) / K ** 2\n",
    "gammas_k2['sum'] = gammas_k2.sum(axis=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "gammas_k2.plot(figsize=(10, 5), cmap='coolwarm')\n",
    "plt.xlabel('index level')\n",
    "plt.ylabel('$K^2$ weighted dollar gamma');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<p style=\"font-family: monospace;\">Squared strike-weighted, added Dollar Gamma values."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As the previous figure shows, this approach finally yields a constant dollar gamma value between strikes of 75 and 150 at least. Let us have a final look at a more dense grid of option strikes since the theoretical result is based on infinite strips of options. The graphical output is shown in the following figure."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "## more dense strike range\n",
    "strike_range = range(10, 350, 5)\n",
    "gammas_k2 = pd.DataFrame()\n",
    "for K in strike_range:\n",
    "    gammas_k2['K=%d' % K] = dollar_gamma(s_range, K, t, T, r, sigma) / K ** 2\n",
    "gammas_k2['sum'] = gammas_k2.sum(axis=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "gammas_k2.plot(figsize=(10, 5), legend=False,\n",
    "              cmap='coolwarm')\n",
    "plt.xlabel('index level')\n",
    "plt.ylabel('$K^2$ weighted dollar gamma');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<p style=\"font-family: monospace;\">Strike-weighted, added Dollar Gamma values."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This numerical example shows a constant dollar gamma over a much wider range from about 25 to beyond 200. This further supports the theoretical result and the replication approach."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## VSTOXX as Volatility Index"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The VSTOXX volatility index measures the implied total variance across all options written on the EURO STOXX 50 stock index for a given time-to-maturity. Another interpretation is that the VSTOXX gives the fair variance swap rate for a variance swap with the respective maturity. The major index with symbol `V2TX` has a fixed time-to-maturity of 30 days and is calculated by the interpolation of two sub-indexes. Sub-indexes are calculated for a number of fixed maturity dates."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Assume now the following setting. Given are the discounted, i.e. time $t$, prices $C_i, i=0,...,n,$ of a series of European call options on the EURO STOXX 50 stock index with fixed time-to-maturity $T$ and strike prices $K_i, i=0,...,n,$ as well as the discounted prices $P_i, i=0,...,n,$ of a series of European put options with the same time-to-maturity and strike prices. Let further hold $K_i < K_{i+1}$ for all $i \\in \\{0,....,n-1\\}$. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The value of the VSTOXX (sub-)index $V$ at $t=0$ is defined by\n",
    "\n",
    "$$\n",
    "V \\equiv 100\\cdot\\sqrt{\\hat{\\sigma}^2}\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "where\n",
    "\n",
    "$$\n",
    " \\hat{\\sigma}^2 \\equiv \\frac{2}{T} \\sum_{i=0}^n \\frac{\\Delta K_i}{{K_i}^2} e^{rT} M_i - \\frac{1}{T}\\left( \\frac{F}{K_*}-1\\right)^2\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "with\n",
    "\n",
    "\\begin{eqnarray}\n",
    "\\Delta K_i &=& \\left\\{\n",
    "\\begin{array}{ll} K_1-K_0, & \\mbox{for } i=0 \\nonumber\\\\\n",
    "         \\frac{K_{i+1}-K_{i-1}}{2}, &  \\mbox{for } i = 1,...,n-1\\\\      \n",
    "         K_n-K_{n-1}, & \\mbox{for } i=n \\end{array}\n",
    "         \\right.  \\nonumber\\\\ \n",
    " F \t    &=& K_j+ e^{rT}|C_j-P_j|,  \\mbox{ where } j=\\displaystyle \\min_{i \\in \\{0,...,n\\}}\\{|C_i-P_i|\\} \\nonumber\\\\\n",
    "K_*     &=& \\displaystyle \\max_{ K_{i}, i \\in \\{0,...,n\\}} \\{K_i < F \\} \\nonumber\\\\\n",
    "M_i &=& \\left\\{\n",
    "\t\\begin{array}{ll} P_i, & \\mbox{for } K_i<K_* \\\\ \n",
    "\t\\frac{P_i-C_i}{2}, &  \\mbox{for } K_i=K_*\\\\ \n",
    "\tC_i, & \\mbox{for } K_i>K_* \\end{array} \\right. \\nonumber \n",
    "\\end{eqnarray}\n",
    "\n",
    "\n",
    "and $r$ the constant risk-free short rate appropriate for time-to-maturity $T$."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It is to be shown that the defining equation for $\\hat{\\sigma}^2$ is indeed a valid approximation for total variance. To this end, we combine the above equations for the log contract and the total variance to obtain\n",
    "\n",
    "\\begin{eqnarray}\n",
    "\\hat{\\sigma}^2 &=& -2\\cdot\\left(-\\int_{0}^{F} P(S_{t},K,T) \\frac{dK}{K^{2}}\n",
    " - \\int_{F}^{\\infty} C(S_{t},K,T) \\frac{dK}{K^{2}} \\right)\\cdot e^{rT} \\nonumber\\\\\n",
    "\\Leftrightarrow \\frac{\\hat{\\sigma}^2 T}{2e^{rT}} &=& \\int_{0}^{F} P(S_{t},K,T) \\frac{dK}{K^{2}}\n",
    "+ \\int_{F}^{\\infty} C(S_{t},K,T) \\frac{dK}{K^{2}} \\nonumber\\\\\n",
    "&=& \\int_{0}^{K_*} P(S_{t},K,T) \\frac{dK}{K^{2}}\n",
    "+ \\int_{K_*}^{\\infty} C(S_{t},K,T) \\frac{dK}{K^{2}}\\nonumber\\\\\n",
    "&+& \\int_{K_*}^{F} \\left[P(S_{t},K,T)-C(S_{t},K,T)\\right] \\frac{dK}{K^{2}}\\nonumber\\\\\n",
    "&=& \\int_{0}^{\\infty} M(S_{t},K,T) \\frac{dK}{K^{2}}+ \\int_{K_*}^{F}e^{-rT} \\left[K-F\\right] \\frac{dK}{K^{2}}\\nonumber\n",
    "\\end{eqnarray}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The last term follows from the observation that only the call option is in-the-money, i.e. $e^{-rT}[F-K]>0$, given the integration boundaries. Then\n",
    "\n",
    "\\begin{eqnarray}\n",
    "\\hat{\\sigma}^2 &=& \\frac{2}{T} \\int_{0}^{\\infty} e^{rT} M(S_{t},K,T) \\frac{dK}{K^{2}}+ \\frac{2}{T} \\frac{1}{K_*^{2}}  \\int_{K_*}^{F} \\left[K-F\\right]dK\\nonumber\\\\\n",
    "&=& \\frac{2}{T} \\int_{0}^{\\infty} e^{rT} M(S_{t},K,T) \\frac{dK}{K^{2}} - \\frac{1}{T} \\frac{(K_*-F)^2}{K_*^{2}}\\nonumber\n",
    "\\end{eqnarray}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that\n",
    "\n",
    "\\begin{eqnarray}\n",
    "\\frac{(K_*-F)^2}{K_*^2}&=&\\frac{K_*^2-2K_*F+F^2}{K_*^2}\\nonumber\\\\\n",
    "&=& \\frac{F^2}{K_*^2}-\\frac{2F}{K_*}+1\\nonumber\\\\\n",
    "&=& \\left(\\frac{F}{K_*}-1\\right)^2\\nonumber\n",
    "\\end{eqnarray}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A possible discretization for the integral then is\n",
    "\n",
    "$$\n",
    "\\hat{\\sigma}^{2}\\approx \\frac{2}{T} \\sum_{i=0}^{n} \\frac{\\Delta K_{i}}{K_{i}^{2}} e^{rT} M_i  - \\frac{1}{T} \\left( \\frac{F}{K_*}-1 \\right)^2\n",
    "$$\n",
    "\n",
    "giving the defining equation for $\\hat{\\sigma}^2$."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The calculation of implied volatilities, or variances, naturally relies on some option pricing model, like the one of Black-Scholes-Merton (1973). By contrast, the VSTOXX and VIX volatility index calculation only takes as input market-observed options prices. This is possible since realized variance at a given future date can be replicated by strips of European call and put prices maturing at the same date. The realized volatility can then be extracted by taking the square root of the realized variance. The calculation of the VSTOXX and VIX avoids a \"model-bias\" and uses standard market practice for the valuation of important variance related instruments, like variance swaps."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Conclusions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This chapter introduces the elegant theory of the model-free replication of realized variance and variance swaps which dates back at least to Breeden and Litzenberger (1978). The role of log contracts and constant dollar gamma positions is discussed. Numerical examples also illustrate how to construct constant dollar gamma options positions in practice. Finally, based on this theory the definition of the VSTOXX and VIX volatility indexes is presented and justified. Subsequent chapters draw in different ways on these cornerstones in the theory of volatility and variance modeling, measuring and trading. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"http://hilpisch.com/tpq_logo.png\" alt=\"The Python Quants\" width=\"35%\" align=\"right\" border=\"0\"><br>\n",
    "\n",
    "<a href=\"http://tpq.io\" target=\"_blank\">http://tpq.io</a> | <a href=\"http://twitter.com/dyjh\" target=\"_blank\">@dyjh</a> | <a href=\"mailto:team@tpq.io\">team@tpq.io</a>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
